package ru.aptu.gsp_banking.snmp;

import org.snmp4j.*;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import java.io.*;
import java.util.Properties;

public class Sender {
    // The file is located in src/main/webapp/WEB-INF/classes
    private static final String CONFIG_FILE = "/snmp_agent.properties";

    private static TransportMapping transportMapping;
    private static Snmp snmp;
    private static CommunityTarget communityTarget;
    
    private static OID oid;

    static {
        try {
            transportMapping = new DefaultUdpTransportMapping();
        } catch (IOException e) {
            e.printStackTrace();
        }
        snmp = new Snmp(transportMapping);
        communityTarget = new CommunityTarget();

        InputStream inputStream = Sender.class.getResourceAsStream(CONFIG_FILE);

        Properties properties = new Properties();

        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        oid = new OID(properties.getProperty("message.oid"));

        communityTarget.setCommunity(new OctetString("public"));
        communityTarget.setAddress(new UdpAddress(properties.getProperty("sender.address")));
        communityTarget.setVersion(SnmpConstants.version2c);
    }

    public synchronized static void sendV2cTrap(String message)
    {
        PDU request = new PDU();
        request.setType(PDU.TRAP);

        request.add(new VariableBinding(oid, new OctetString(message)));

        try {
            snmp.send(request, communityTarget);
        } catch (IOException e) {
            System.err.println("Error in sending SNMP trap");
        }
    }
}
